package cn.pegasus.teamwork.appinterface.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import cn.pegasus.teamwork.appinterface.session.MySessionContext;
import cn.pegasus.teamwork.appinterface.util.ParameterEunm;
import cn.pegasus.teamwork.appinterface.util.ReturnRsUtils;
import cn.pegasus.teamwork.pegasus.entity.BussUserInfo;

/**
 * 
 * @ClassName: SecurityInterceptor
 * @Description: spring拦截器
 * @author buyuer
 * @date 2015年10月8日 下午3:34:53
 * 
 */
public class SecurityInterceptor implements HandlerInterceptor {

	 private static final String LOGIN_URL = "/login.htm";

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
		
		if(req.getParameter("userCertificate") != null){
			String sessionId = req.getParameter("userCertificate");
			HttpSession session = MySessionContext.getInstance().getSession(sessionId);
			if (session != null) {
				// 从session 里面获取用户名的信息
				BussUserInfo user =((BussUserInfo)session.getAttribute("users"));
				if(user !=  null ){
					return true;
				}
			} else {
				// 判断如果没有取到用户信息，就跳转到登陆页面，提示用户进行登陆
				res.setCharacterEncoding("没有权限进行访问"); // .sendRedirect(LOGIN_URL);
				res.setCharacterEncoding("UTF-8");
				res.setContentType("application/json; charset=utf-8");
				PrintWriter out = null;
				try {
					out = res.getWriter();
					out.append(JSON.toJSONString(ReturnRsUtils.resultBackString(ParameterEunm.ERROR_LOGIN_CODE, null)));
					return false;
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (out != null) {
						out.close();
					}
				}
			}

		} else {
			// 判断如果没有取到用户信息，就跳转到登陆页面，提示用户进行登陆
			res.sendRedirect(LOGIN_URL);
			res.setCharacterEncoding("UTF-8");
			res.setContentType("application/json; charset=utf-8");
			PrintWriter out = null;
			try {
				out = res.getWriter();
				out.append(JSON.toJSONString(ReturnRsUtils.resultBackString(ParameterEunm.ERROR_LOGIN_CODE, null)));
				return false;
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (out != null) {
					out.close();
				}
			}
		}	
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse res, Object arg2, ModelAndView arg3)
			throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object arg2, Exception arg3)
			throws Exception {
	}

}
